// GatewayPrepareController.java
package com.example.gymlearning.controller;

import com.example.gymlearning.entity.KnowledgePoint;
import com.example.gymlearning.entity.QuizQuestion;
import com.example.gymlearning.service.KnowledgePointService;
import com.example.gymlearning.service.QuizQuestionService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Controller
@RequestMapping("/practice/gateway")
@RequiredArgsConstructor
public class GatewayPrepareController {

    private final KnowledgePointService knowledgePointService;
    private final QuizQuestionService quizQuestionService;
    private final ObjectMapper objectMapper;

    // 辅助方法：安全 URL 编码（Java 8 兼容）
    private String urlEncode(String value) {
        if (value == null || value.isEmpty()) {
            return "";
        }
        try {
            return URLEncoder.encode(value, "UTF-8");
        } catch (Exception e) {
            log.warn("URL 编码失败，返回原始字符串: {}", value, e);
            return value;
        }
    }

    @GetMapping("/prepare")
    public String prepareGateway(@RequestParam Long pointId, Model model) {
        try {
            KnowledgePoint currentPoint = knowledgePointService.queryById(pointId);
            if (currentPoint == null) {
                String error = urlEncode("知识点不存在");
                return "redirect:/practice/choice?pointId=" + pointId + "&error=" + error;
            }

            int practiceQuestionCount = quizQuestionService.getPracticeQuestionCount(pointId);
            int formalQuestionCount = quizQuestionService.getFormalQuestionCount(pointId);

            model.addAttribute("point", currentPoint);
            model.addAttribute("practiceQuestionCount", practiceQuestionCount);
            model.addAttribute("formalQuestionCount", formalQuestionCount);
            model.addAttribute("pointId", pointId);

            return "gateway-prepare";
        } catch (Exception e) {
            log.error("加载闯关准备页面失败", e);
            String error = urlEncode("加载失败");
            return "redirect:/practice/choice?pointId=" + pointId + "&error=" + error;
        }
    }

    @GetMapping("/practice")
    public String startPractice(@RequestParam Long pointId, Model model) {
        try {
            KnowledgePoint currentPoint = knowledgePointService.queryById(pointId);
            Long sessionId = quizQuestionService.createPracticeSession(pointId);
            List<QuizQuestion> practiceQuestions = quizQuestionService.getPracticeQuestions(pointId);

            // 添加调试信息
            log.info("练习模式 - 知识点ID: {}, 题目数量: {}", pointId, practiceQuestions.size());
            practiceQuestions.forEach(q -> log.info("题目ID: {}, 内容: {}, usageType: {}",
                    q.getId(), q.getContent(), q.getUsageType()));

            model.addAttribute("point", currentPoint);
            model.addAttribute("sessionId", sessionId);
            model.addAttribute("questions", practiceQuestions);
            model.addAttribute("isPractice", true);
            model.addAttribute("pointId", pointId);

            return "practice-gateway-session";
        } catch (Exception e) {
            log.error("开始练习模式失败", e);
            String error = urlEncode("开始练习失败: " + e.getMessage());
            return "redirect:/practice/gateway/prepare?pointId=" + pointId + "&error=" + error;
        }
    }

    @GetMapping("/formal")
    public String startFormal(@RequestParam Long pointId, Model model) {
        try {
            KnowledgePoint currentPoint = knowledgePointService.queryById(pointId);
            Long sessionId = quizQuestionService.createFormalSession(pointId);
            List<QuizQuestion> formalQuestions = quizQuestionService.getFormalQuestions(pointId);

            // 添加调试信息
            log.info("正式模式 - 知识点ID: {}, 题目数量: {}", pointId, formalQuestions.size());
            formalQuestions.forEach(q -> log.info("题目ID: {}, 内容: {}, usageType: {}",
                    q.getId(), q.getContent(), q.getUsageType()));

            model.addAttribute("point", currentPoint);
            model.addAttribute("sessionId", sessionId);
            model.addAttribute("questions", formalQuestions);
            model.addAttribute("isPractice", false);
            model.addAttribute("pointId", pointId);

            return "practice-gateway-session";
        } catch (Exception e) {
            log.error("开始正式闯关失败", e);
            String error = urlEncode("开始闯关失败: " + e.getMessage());
            return "redirect:/practice/gateway/prepare?pointId=" + pointId + "&error=" + error;
        }
    }

    // 在 GatewayPrepareController.java 中添加以下接口

    @GetMapping("/questions")
    @ResponseBody
    public ResponseEntity<?> getQuestions(
            @RequestParam Long pointId,
            @RequestParam boolean isPractice
    ) {
        try {
            if (pointId == null) {
                return ResponseEntity.badRequest().body("pointId不能为空");
            }

            List<QuizQuestion> questions;
            if (isPractice) {
                questions = quizQuestionService.getPracticeQuestions(pointId);
            } else {
                questions = quizQuestionService.getFormalQuestions(pointId);
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("questions", questions);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取题目失败", e);
            return ResponseEntity.status(500).body("获取题目失败: " + e.getMessage());
        }
    }

    @GetMapping("/api/points/{pointId}")
    @ResponseBody
    public ResponseEntity<?> getPointInfo(@PathVariable Long pointId) {
        try {
            if (pointId == null) {
                return ResponseEntity.badRequest().body("pointId不能为空");
            }

            KnowledgePoint point = knowledgePointService.queryById(pointId);
            if (point == null) {
                return ResponseEntity.notFound().build();
            }

            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", point);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            log.error("获取知识点信息失败", e);
            return ResponseEntity.status(500).body("获取知识点信息失败: " + e.getMessage());
        }
    }
    @PostMapping("/complete-practice")
    public String completePractice(@RequestParam(required = false) Long sessionId,
                                   @RequestParam Long pointId) {
        try {
            quizQuestionService.completeSession(sessionId);
            return "redirect:/practice/gateway/formal?pointId=" + pointId;
        } catch (Exception e) {
            log.error("完成练习模式失败", e);
            String error = urlEncode("完成练习失败");
            return "redirect:/practice/gateway/prepare?pointId=" + pointId + "&error=" + error;
        }
    }

    @PostMapping("/submit-formal")
    public String submitFormal(@RequestParam Long sessionId,
                               @RequestParam Long pointId,
                               @RequestParam Integer score,
                               @RequestParam Integer totalQuestions,
                               @RequestParam Integer correctAnswers,
                               Model model) {
        try {
            boolean isPassed = quizQuestionService.completeFormalSession(sessionId, score, correctAnswers, totalQuestions);
            if (isPassed) {
                knowledgePointService.unlockNextPoint(pointId);
            }
            model.addAttribute("isPassed", isPassed);
            model.addAttribute("score", score);
            model.addAttribute("totalQuestions", totalQuestions);
            model.addAttribute("correctAnswers", correctAnswers);
            model.addAttribute("pointId", pointId);

            return "practice/gateway-result";
        } catch (Exception e) {
            log.error("提交正式闯关失败", e);
            String error = urlEncode("提交失败");
            return "redirect:/practice/gateway/prepare?pointId=" + pointId + "&error=" + error;
        }
    }

    private String serializeToJson(Object obj) {
        if (obj == null || objectMapper == null) {
            return "[]";
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            log.warn("JSON 序列化失败", e);
            return "[]";
        }
    }
}